<?php
namespace Admin\Domain;

use Portal\Model\Admin as AdminModel;
use Admin\Model\RightsRBACPolicy as RightsRBACPolicyModel;
use PhalApi\Exception\BadRequestException;

class Rights {

    public function refreshPolicyCsv() {
        $di = \PhalApi\DI();
        $csvPath = $di->iadminosRights->getPolicyCsvPath();
        if (!is_writeable($csvPath)) {
            throw new BadRequestException('CSV文件缺少写入权限：' . $csvPath);
        }

        $policyContent = '';

        // 加载全部权限策略
        $policyModel = new RightsRBACPolicyModel();
        $policyList = $policyModel->getList(null, array(), '*', null, 1, 10000);
        foreach ($policyList as $it) {
            $policyContent .= implode(', ', array($it['policy'], $it['role'], $it['class_name'], $it['action_name'])) . PHP_EOL;
        }
        $policyContent .= "" . PHP_EOL;

        // 加载全部角色
        $adminModel = new AdminModel();
        $roleMaps = $adminModel->getAllUsernameAndRoleMap();
        foreach ($roleMaps as $username => $role) {
            $policyContent .= implode(', ', array('g', $username, $role)) . PHP_EOL;
        }
        // var_dump($roleMaps, $policyList, $policyContent);

        file_put_contents($csvPath, $policyContent);
    }
}
